<!DOCTYPE html>
<html lang=zh>
<head>
    <meta name="baidu-site-verification" content="lKl7jYajUz" />
    <meta charset="utf-8">
    
    <title>JMS学习（三）----- ActiveMQ简单的HelloWorld实例 | 迷失的男孩</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="keywords" content="火龙战士,zhengweishan,郑伟山的博客，bolg,博客">
    <meta name="description" content="开发环境我使用的是ActiveMQ 5.13.3 Release的Windows版，官网最新版是ActiveMQ 5.13.4 Release，大家可以自行下载，下载地址。
需要注意的是，开发时候，要将apache-activemq-5.13.3-bin.zip解压缩后里面的activemq-all-5.13.3.jar包加入到classpath下面，这个包包含了所有jms接口api的实现。
项目">
<meta property="og:type" content="article">
<meta property="og:title" content="JMS学习（三）----- ActiveMQ简单的HelloWorld实例">
<meta property="og:url" content="http://zhengweishan.oschina.io/2017/01/24/JMS学习（三）ActiveMQ简单的HelloWorld实例/index.html">
<meta property="og:site_name" content="迷失的男孩">
<meta property="og:description" content="开发环境我使用的是ActiveMQ 5.13.3 Release的Windows版，官网最新版是ActiveMQ 5.13.4 Release，大家可以自行下载，下载地址。
需要注意的是，开发时候，要将apache-activemq-5.13.3-bin.zip解压缩后里面的activemq-all-5.13.3.jar包加入到classpath下面，这个包包含了所有jms接口api的实现。
项目">
<meta property="og:image" content="http://i.imgur.com/pPp8eMU.png">
<meta property="og:image" content="http://i.imgur.com/g71ThMY.png">
<meta property="og:image" content="http://i.imgur.com/pxZmjXj.png">
<meta property="og:image" content="http://i.imgur.com/a7R59y3.png">
<meta property="og:image" content="http://i.imgur.com/AQpd48x.png">
<meta property="og:image" content="http://i.imgur.com/T66lsxc.png">
<meta property="og:image" content="http://i.imgur.com/l63Vrxg.png">
<meta property="og:image" content="http://i.imgur.com/44UYCg0.png">
<meta property="og:updated_time" content="2017-03-01T08:40:01.239Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JMS学习（三）----- ActiveMQ简单的HelloWorld实例">
<meta name="twitter:description" content="开发环境我使用的是ActiveMQ 5.13.3 Release的Windows版，官网最新版是ActiveMQ 5.13.4 Release，大家可以自行下载，下载地址。
需要注意的是，开发时候，要将apache-activemq-5.13.3-bin.zip解压缩后里面的activemq-all-5.13.3.jar包加入到classpath下面，这个包包含了所有jms接口api的实现。
项目">
<meta name="twitter:image" content="http://i.imgur.com/pPp8eMU.png">
    

    
        <link rel="alternate" href="/atom.xml" title="迷失的男孩" type="application/atom+xml" />
    

    
        <link rel="icon" href="/css/images/favicon.ico" />
    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">
    <link rel="alternate stylesheet" href="http://cdn.bootcss.com/highlight.js/8.0/styles/monokai_sublime.min.css" title="highlight" />
    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    
        <script>
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?eb23f1849f20e62c924d275e4edef134";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
</script>

    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">迷失的男孩</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">主页</a>
                
                    <a class="main-nav-link" href="/archives">归档</a>
                
                    <a class="main-nav-link" href="/categories">分类</a>
                
                    <a class="main-nav-link" href="/tags">标签</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.jpg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/.">主页</a></td>
                
                    <td><a class="main-nav-link" href="/archives">归档</a></td>
                
                    <td><a class="main-nav-link" href="/categories">分类</a></td>
                
                    <td><a class="main-nav-link" href="/tags">标签</a></td>
                
                    <td><a class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.jpg" />
            <h2 id="name">迷失的男孩</h2>
            <h3 id="title">为API生，为框架死，为debug奋斗一辈子，吃符号亏，上大小写的当，最后死在需求上。</h3>
            <span id="location"><i class="fa fa-map-marker"></i>中国, 北京</span>
            <a id="follow" target="_blank" href="https://github.com/wesley5201314">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                25
                <span>文章</span>
            </div>
            <div class="article-info-block">
                13
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="https://github.com/wesley5201314" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="https://git.oschina.net/zhengweishan" target="_blank" title="git" class=tooltip>
                            <i class="fa fa-git"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/css/images/weixin.png" target="_blank" title="weixin" class=tooltip>
                            <i class="fa fa-weixin"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="http://weibo.com/wesley5201314" target="_blank" title="weibo" class=tooltip>
                            <i class="fa fa-weibo"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/atom.xml" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
        <div class="base-info" style="text-align:center">
        <span style="color:#38b7ea">今天是：
                 <script type="text/javascript">
                　　today=new Date(); 
                    var tdate,tday, x,year; 
                    var x = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五","星期六");
                　　var MSIE=navigator.userAgent.indexOf("MSIE");
                    if(MSIE != -1)
                    　year =(today.getFullYear());
                    else
                    　year = (today.getYear()+1900);
                    　tdate= year+ "年" + (today.getMonth() + 1 ) + "月" + today.getDate() + "日" + " " + x[today.getDay()];
                    　document.write(tdate); 
                </script>
        </span> 
        </div>
        <div class="base-info" style="text-align:center">
                <span style="color:#38b7ea;"><script type="text/javascript">
                    today=new Date();
                    var day; var date; var hello;
                    hour=new Date().getHours()
                    if(hour < 6)hello='  凌晨好! '
                    else if(hour < 9)hello=' 早上好! '
                    else if(hour < 12)hello=' 上午好! '
                    else if(hour < 14)hello=' 中午好! '
                    else if(hour < 17)hello=' 下午好! '
                    else if(hour < 19)hello=' 傍晚好! '
                    else if(hour < 22)hello=' 晚上好! '
                    else {hello='夜深了! '}
                    var webUrl = webUrl;
                    document.write(' '+hello);
                </script>
                </span>
            <span id="busuanzi_container_site_uv">
                您是本站第<span id="busuanzi_value_site_uv" class="foot-count"></span>位访客
            </span>
        </div>
    </div>
</aside>

            
            <section id="main"><article id="post-JMS学习（三）ActiveMQ简单的HelloWorld实例" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            JMS学习（三）----- ActiveMQ简单的HelloWorld实例
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/2017/01/24/JMS学习（三）ActiveMQ简单的HelloWorld实例/">
            <time datetime="2017-01-23T16:00:00.000Z" itemprop="datePublished">2017-01-24</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/JMS/">JMS</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/ActiveMQ/">ActiveMQ</a>, <a class="tag-link" href="/tags/JMS/">JMS</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <h2 id="开发环境"><a href="#开发环境" class="headerlink" title="开发环境"></a>开发环境</h2><p>我使用的是ActiveMQ 5.13.3 Release的Windows版，官网最新版是ActiveMQ 5.13.4 Release，大家可以自行下载，<a href="http://activemq.apache.org/download-archives.html" target="_blank" rel="external">下载地址</a>。</p>
<p>需要注意的是，开发时候，要将apache-activemq-5.13.3-bin.zip解压缩后里面的activemq-all-5.13.3.jar包加入到classpath下面，这个包包含了所有jms接口api的实现。</p>
<p>项目截图：</p>
<p><img src="http://i.imgur.com/pPp8eMU.png" alt=""></p>
<h2 id="ActiviteMQ消息有3中形式"><a href="#ActiviteMQ消息有3中形式" class="headerlink" title="ActiviteMQ消息有3中形式"></a>ActiviteMQ消息有3中形式</h2><p><strong>JMS 公共 ———-点对点域 ———-发布/订阅域</strong></p>
<p>ConnectionFactory ———- QueueConnectionFactory ———- TopicConnectionFactory</p>
<p>Connection ———- QueueConnection ———- TopicConnection</p>
<p>Destination ———- Queue  ———- Topic</p>
<p>Session ———- QueueSession ———- TopicSession</p>
<p>MessageProducer ———- QueueSender ———- TopicPublisher</p>
<p>MessageConsumer ———- QueueReceiver ———- TopicSubscriber</p>
<p>(1)、点对点方式（point-to-point）</p>
<p>点对点的消息发送方式主要建立在 Message Queue,Sender,reciever上，Message Queue 存贮消息，Sneder 发送消息，receive接收消息.具体点就是Sender Client发送Message Queue ,而 receiver Cliernt从Queue中接收消息和”发送消息已接受”到Quere,确认消息接收。消息发送客户端与接收客户端没有时间上的依赖，发送客户端可以在任何时刻发送信息到Queue，而不需要知道接收客户端是不是在运行</p>
<p>(2)、发布/订阅 方式（publish/subscriber Messaging）</p>
<p>发布/订阅方式用于多接收客户端的方式.作为发布订阅的方式，可能存在多个接收客户端，并且接收端客户端与发送客户端存在时间上的依赖。一个接收端只能接收他创建以后发送客户端发送的信息。作为subscriber ,在接收消息时有两种方法，destination的receive方法，和实现message listener 接口的onMessage 方法。</p>
<a id="more"></a>
<h2 id="ActiviteMQ接收和发送消息基本流程"><a href="#ActiviteMQ接收和发送消息基本流程" class="headerlink" title="ActiviteMQ接收和发送消息基本流程"></a>ActiviteMQ接收和发送消息基本流程</h2><p><img src="http://i.imgur.com/g71ThMY.png" alt=""></p>
<p><strong>发送消息的基本步骤：</strong></p>
<p>(1)、创建连接使用的工厂类JMS ConnectionFactory</p>
<p>(2)、使用管理对象JMS ConnectionFactory建立连接Connection，并启动</p>
<p>(3)、使用连接Connection 建立会话Session</p>
<p>(4)、使用会话Session和管理对象Destination创建消息生产者MessageSender</p>
<p>(5)、使用消息生产者MessageSender发送消息</p>
<p><strong>消息接收者从JMS接受消息的步骤</strong></p>
<p>(1)、创建连接使用的工厂类JMS ConnectionFactory</p>
<p>(2)、使用管理对象JMS ConnectionFactory建立连接Connection，并启动</p>
<p>(3)、使用连接Connection 建立会话Session</p>
<p>(4)、使用会话Session和管理对象Destination创建消息接收者MessageReceiver</p>
<p>(5)、使用消息接收者MessageReceiver接受消息，需要用setMessageListener将MessageListener接口绑定到MessageReceiver消息接收者必须实现了MessageListener接口，需要定义onMessage事件方法。</p>
<h3 id="使用JMS方式发送接收消息"><a href="#使用JMS方式发送接收消息" class="headerlink" title="使用JMS方式发送接收消息"></a>使用JMS方式发送接收消息</h3><pre><code>package com.active.mq.demo;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class MQConnectionFactory {

    private  static final  String USERNAME = ActiveMQConnection.DEFAULT_USER;//默认连接用户名
    private  static final  String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认连接密码
    private  static final  String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;//默认连接地址

    private static ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);//连接工厂

    /**
     * 通过连接工厂获取连接
     * @return
     */
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = connectionFactory.createConnection();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return connection;
    }
}

package com.active.mq.demo;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

public class JMSConsumer {


    public static void main(String[] args) {
        Connection connection = null;//连接

        Session session = null;//会话 接受或者发送消息的线程

        Destination destination;//消息的目的地

        MessageConsumer messageConsumer;//消息的消费者

        try {
            //通过连接工厂获取连接
            connection = MQConnectionFactory.getConnection();
            //启动连接
            connection.start();
            //创建session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建一个连接HelloWorld的消息队列
            destination = session.createQueue(&quot;HelloWorld&quot;);
            //创建消息消费者
            messageConsumer = session.createConsumer(destination);

            while (true) {
                TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
                if(textMessage != null){
                    System.out.println(&quot;收到的消息:&quot; + textMessage.getText());
                }else {
                    break;
                }
            }
            //提交回话
            session.commit();

        } catch (JMSException e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if(session !=null){
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


package com.active.mq.demo;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

public class JMSProducer {

    //发送的消息数量
    private static final int SENDNUM = 10;

    public static void main(String[] args) {

        //连接
        Connection connection = null;
        //会话 接受或者发送消息的线程
        Session session = null;
        //消息的目的地
        Destination destination;
        //消息生产者
        MessageProducer messageProducer;


        try {
            //通过连接工厂获取连接
            connection = MQConnectionFactory.getConnection();
            //启动连接
            connection.start();
            //创建session
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            //创建一个名称为HelloWorld的消息队列
            destination = session.createQueue(&quot;HelloWorld&quot;);
            //创建消息生产者
            messageProducer = session.createProducer(destination);
            //发送消息
            sendMessage(session, messageProducer);
            //提交回话
            session.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if(session !=null){
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 发送消息
     * @param session
     * @param messageProducer  消息生产者
     * @throws Exception
     */
    public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception{
        for (int i = 0; i &lt; JMSProducer.SENDNUM; i++) {
            //创建一条文本消息 
            TextMessage message = session.createTextMessage(&quot;发送JMS消息第&quot; + (i + 1) + &quot;条&quot;);
            System.out.println(&quot;发送消息：Activemq 发送JMS消息&quot; + (i + 1));
            //通过消息生产者发出消息 
            messageProducer.send(message);
        }

    }
}
</code></pre><h3 id="Queue队列方式发送点对点消息数据"><a href="#Queue队列方式发送点对点消息数据" class="headerlink" title="Queue队列方式发送点对点消息数据"></a>Queue队列方式发送点对点消息数据</h3><p>在获取工厂类中加入如下代码：</p>
<pre><code>private static QueueConnectionFactory queueConnectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);

/**
 * 通过连接工厂获取连接(Queue方式)
 * @return
 */
public static QueueConnection getQueueConnection(){
    QueueConnection connection = null;
    try {
        connection = queueConnectionFactory.createQueueConnection();
    } catch (JMSException e) {
        e.printStackTrace();
    }
    return connection;
}


//消息生产者
package com.active.mq.demo;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;

public class QueueProducer {
     private static final int SEND_NUM = 10;


    public static void main(String[] args) {
        QueueConnection queueConnection = null;
        QueueSession queueSession = null;
        try {
            // 通过工厂创建一个连接
            queueConnection = MQConnectionFactory.getQueueConnection();
            // 启动连接
            queueConnection.start();
            // 创建一个session会话
            queueSession = queueConnection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Queue queue = queueSession.createQueue(&quot;QueueMsgDemo&quot;);
            // 创建消息发送者
            QueueSender sender = queueSession.createSender(queue);
            // 设置持久化模式
            sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            sendMessage(queueSession, sender);
            // 提交会话
            queueSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭释放资源
            if (queueSession != null) {
                try {
                    queueSession.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (queueConnection != null) {
                try {
                    queueConnection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }


     public static void sendMessage(QueueSession session, QueueSender sender) throws Exception {
            for (int i = 0; i &lt; SEND_NUM; i++) {
                String message = &quot;发送queue消息第&quot; + (i + 1) + &quot;条&quot;;
                //创建一个Map集合信息
                MapMessage map = session.createMapMessage();
                map.setString(&quot;text&quot;, message);
                map.setLong(&quot;time&quot;, System.currentTimeMillis());
                System.out.println(&quot;ActiveMQ 发送queue消息：&quot;+(i + 1));
                sender.send(map);
            }
        }
}

//消费者
package com.active.mq.demo;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;

public class QueueConsumer {

    public static void main(String[] args) {
        QueueConnection queueConnection = null;
        QueueSession queueSession = null;
        try {
            // 通过工厂创建一个连接
            queueConnection = MQConnectionFactory.getQueueConnection();
            // 启动连接
            queueConnection.start();
            // 创建一个session会话
            queueSession = queueConnection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Queue queue = queueSession.createQueue(&quot;QueueMsgDemo&quot;);
            // 创建消息接收者
            QueueReceiver receiver = queueSession.createReceiver(queue);

            receiver.setMessageListener(new MessageListener() {
                public void onMessage(Message msg) {
                    if (msg != null) {
                        MapMessage map = (MapMessage) msg;
                        try {
                            System.out.println(map.getLong(&quot;time&quot;) + &quot;接收到消息#&quot; + map.getString(&quot;text&quot;));
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            // 休眠100ms再关闭
            Thread.sleep(1000 * 100);

            // 提交会话
            queueSession.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭释放资源
            if (queueSession != null) {
                try {
                    queueSession.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (queueConnection != null) {
                try {
                    queueConnection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
</code></pre><h3 id="Topic主题发布和订阅消息"><a href="#Topic主题发布和订阅消息" class="headerlink" title="Topic主题发布和订阅消息"></a>Topic主题发布和订阅消息</h3><p>在获取工厂类中加入如下代码：</p>
<pre><code> private static TopicConnectionFactory topicConnectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);

/**
 * 通过连接工厂获取连接(Topic方式)
 * @return
 */
public static TopicConnection getTopicConnection(){
    TopicConnection topicConnection = null;
    try {
        topicConnection = topicConnectionFactory.createTopicConnection();
    } catch (JMSException e) {
        e.printStackTrace();
    }
    return topicConnection;
}

//生产者
package com.active.mq.demo;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;

public class TopicProducer {
    private static final int SEND_NUM = 10;

    public static void main(String[] args) {
          TopicConnection connection = null;
          TopicSession session = null;
            try {
                // 通过工厂创建一个连接
                connection = MQConnectionFactory.getTopicConnection();
                // 启动连接
                connection.start();
                // 创建一个session会话
                session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
                // 创建一个消息队列
                Topic topic = session.createTopic(&quot;TopicDemo&quot;);
                // 创建消息发送者
                TopicPublisher publisher = session.createPublisher(topic);
                // 设置持久化模式
                publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                sendMessage(session, publisher);
                // 提交会话
                session.commit();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭释放资源
                if (session != null) {
                    try {
                        session.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
    }

    public static void sendMessage(TopicSession session, TopicPublisher publisher) throws Exception {
        for (int i = 0; i &lt; SEND_NUM; i++) {
            String message = &quot;发送Topic消息第&quot; + (i + 1) + &quot;条&quot;;

            MapMessage map = session.createMapMessage();
            map.setString(&quot;text&quot;, message);
            map.setLong(&quot;time&quot;, System.currentTimeMillis());
            System.out.println(&quot;ActiveMQ 发送Topic消息：&quot;+(i + 1));
            publisher.send(map);
        }
    }
}

//消费者
package com.active.mq.demo;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;

public class TopicConsumer {

    public static void main(String[] args) {
        TopicConnection connection = null;
        TopicSession session = null;
        try {
            // 通过工厂创建一个连接
            connection = MQConnectionFactory.getTopicConnection();
            // 启动连接
            connection.start();
            // 创建一个session会话
            session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Topic topic = session.createTopic(&quot;TopicDemo&quot;);
            // 创建消息消费者
            TopicSubscriber subscriber = session.createSubscriber(topic);

            subscriber.setMessageListener(new MessageListener() { 
                public void onMessage(Message msg) { 
                    if (msg != null) {
                        MapMessage map = (MapMessage) msg;
                        try {
                            System.out.println(map.getLong(&quot;time&quot;) + &quot;Topic接收消息#&quot; + map.getString(&quot;text&quot;));
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                } 
            }); 
            // 休眠100ms再关闭
            Thread.sleep(1000 * 100); 
            // 提交会话
            session.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭释放资源
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
</code></pre><h2 id="运行"><a href="#运行" class="headerlink" title="运行"></a>运行</h2><p>以使用JMS方式发送接收消息为例说明<br>1、首先，启动ActiveMQ<br>2、运行发送者，eclipse控制台输出，如下图：</p>
<p><img src="http://i.imgur.com/pxZmjXj.png" alt=""><br>3、查看ActiveMQ服务器，Queues内容如下：</p>
<p><img src="http://i.imgur.com/a7R59y3.png" alt=""></p>
<p>我们可以看到创建了一个名称为HelloWorld的消息队列，队列中有10条消息未被消费，我们也可以通过Browse查看是哪些消息，如果这些队列中的消息，被删除，消费者则无法消费。</p>
<p><img src="http://i.imgur.com/AQpd48x.png" alt=""></p>
<p>4、运行一下消费者，eclipse控制台打印消息，如下：</p>
<p><img src="http://i.imgur.com/T66lsxc.png" alt=""></p>
<p>5、我们在查看一下ActiveMQ服务器，Queues内容如下：</p>
<p><img src="http://i.imgur.com/l63Vrxg.png" alt=""></p>
<p>我们可以看到HelloWorld的消息队列发生变化，多一个消息者，队列中的10条消息被消费了，点击Browse查看，已经为空了。<br>点击Active Consumers，我们可以看到这个消费者的详细信息。</p>
<p><img src="http://i.imgur.com/44UYCg0.png" alt=""></p>
<p>实例到此就结束了，大家可以自己多看点ActiveMQ服务器的内容，进一步熟悉ActiveMQ。</p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    
        <a href="http://zhengweishan.oschina.io/2017/01/24/JMS学习（三）ActiveMQ简单的HelloWorld实例/#comments" class="article-comment-link disqus-comment-count" data-disqus-url="http://zhengweishan.oschina.io/2017/01/24/JMS学习（三）ActiveMQ简单的HelloWorld实例/">评论</a>
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/2017/01/25/JMS学习（四）Spring和ActiveMQ整合的完整实例/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    JMS学习（四）-----Spring和ActiveMQ整合的完整实例
                
            </div>
        </a>
    
    
        <a href="/2017/01/23/JMS学习（二）ActiveMQ简单介绍以及安装/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">JMS学习（二）----- ActiveMQ简单介绍以及安装</div>
        </a>
    
</nav>


    
</article>


    
    <section id="comments">
    
        
    <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>

    
    </section>

</section>
            
                <aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="">
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/03/27/CountDownLatch/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/并发/">并发</a></p>
                            <p class="item-title"><a href="/2017/03/27/CountDownLatch/" class="title">java并发包里的CountDownLatch的用法</a></p>
                            <p class="item-date"><time datetime="2017-03-26T16:00:00.000Z" itemprop="datePublished">2017-03-27</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/03/24/spring-boot-demo/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot/">SpringBoot</a></p>
                            <p class="item-title"><a href="/2017/03/24/spring-boot-demo/" class="title">spring boot + mybatis + quartz + druid + swagger2</a></p>
                            <p class="item-date"><time datetime="2017-03-23T16:00:00.000Z" itemprop="datePublished">2017-03-24</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/03/23/boy-rpc-framework/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/rpc/">rpc</a></p>
                            <p class="item-title"><a href="/2017/03/23/boy-rpc-framework/" class="title">分布式rpc框架</a></p>
                            <p class="item-date"><time datetime="2017-03-22T16:00:00.000Z" itemprop="datePublished">2017-03-23</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/02/10/（六）Tomcat_7.0.70生命周期管理/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/Tomcat源码/">Tomcat源码</a></p>
                            <p class="item-title"><a href="/2017/02/10/（六）Tomcat_7.0.70生命周期管理/" class="title">Tomcat源码学习（六）--Tomcat_7.0.70 生命周期管理</a></p>
                            <p class="item-date"><time datetime="2017-02-09T16:00:00.000Z" itemprop="datePublished">2017-02-10</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/2017/02/09/（五）Tomcat_7.0.70类加载体系/" class="thumbnail">
    
    
        <span class="thumbnail-image thumbnail-none"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/Tomcat源码/">Tomcat源码</a></p>
                            <p class="item-title"><a href="/2017/02/09/（五）Tomcat_7.0.70类加载体系/" class="title">Tomcat源码学习（五）-- Tomcat_7.0.70 类加载体系分析</a></p>
                            <p class="item-date"><time datetime="2017-02-08T16:00:00.000Z" itemprop="datePublished">2017-02-09</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Elasticsearch/">Elasticsearch</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JAVA/">JAVA</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JMS/">JMS</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JVM/">JVM</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot/">SpringBoot</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tomcat源码/">Tomcat源码</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/kafka/">kafka</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/rpc/">rpc</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/并发/">并发</a><span class="category-list-count">1</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/ActiveMQ/" style="font-size: 16.67px;">ActiveMQ</a> <a href="/tags/Elasticsearch学习/" style="font-size: 13.33px;">Elasticsearch学习</a> <a href="/tags/GC/" style="font-size: 13.33px;">GC</a> <a href="/tags/Hexo/" style="font-size: 10px;">Hexo</a> <a href="/tags/JAVA/" style="font-size: 16.67px;">JAVA</a> <a href="/tags/JMS/" style="font-size: 16.67px;">JMS</a> <a href="/tags/JVM/" style="font-size: 13.33px;">JVM</a> <a href="/tags/Reflection/" style="font-size: 10px;">Reflection</a> <a href="/tags/SpingBoot/" style="font-size: 10px;">SpingBoot</a> <a href="/tags/kafka/" style="font-size: 16.67px;">kafka</a> <a href="/tags/rpc-分布式/" style="font-size: 10px;">rpc 分布式</a> <a href="/tags/tomcat/" style="font-size: 20px;">tomcat</a> <a href="/tags/并发，CountDownLatch/" style="font-size: 10px;">并发，CountDownLatch</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
                        <a href="http://hexo.io">Hexo</a>
                    </li>
                
                    <li>
                        <a href="https://longfeizheng.github.io/">龙飞</a>
                    </li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>
            
        </div>
        <footer id="footer">
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2017 郑伟山 版权所有<br> 
            由 <a href="http://hexo.io/" target="_blank">Hexo</a> 强力驱动 &brvbar; 主题 -- <a href="https://github.com/ppoffice/hexo-theme-icarus">Icarus</a><br>
            
        </div>
		<div class="inner">
        	<span id="busuanzi_container_site_pv">
    			本站总访问量<span id="busuanzi_value_site_pv" class="foot-count"></span>次
			</span>
		</div>
    </div>
<script src="http://cdn.bootcss.com/highlight.js/8.0/highlight.min.js"></script>
</footer>
        
    
    <script>
    var disqus_config = function () {
        
            this.page.url = 'http://zhengweishan.oschina.io/2017/01/24/JMS学习（三）ActiveMQ简单的HelloWorld实例/';
        
        this.page.identifier = 'JMS学习（三）ActiveMQ简单的HelloWorld实例';
    };
    (function() { 
        var d = document, s = d.createElement('script');  
        s.src = '//' + 'hexo-theme-icarus' + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>



    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>